package timing.ukulele.form.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.form.persistent.FormTemplateHistory;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.item.ItemData;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.form.client.ItemClient;
import timing.ukulele.form.client.SystemClient;
import timing.ukulele.form.mapper.FromTemplateHistoryMapper;
import timing.ukulele.persistent.service.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FormTemplateHistoryService extends BaseService<FromTemplateHistoryMapper, FormTemplateHistory> {

    @Resource
    private SystemClient systemClient;
    @Resource
    private ItemClient itemClient;


    /**
     * 获取分页
     *
     * @param name    查询名称
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<FormTemplateHistory> page(String name, String system, int current, int size, HashMap<String, Object> map) {
        Page<FormTemplateHistory> page = new Page<>(current, size);
        LambdaQueryWrapper<FormTemplateHistory> qw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            qw.like(FormTemplateHistory::getName, name);
        }
        List<Long> systemIds = null;
        if (!"".equals(system)) {
            String[] split = system.split(",");
            if (!"0".equals(split[0])) {
                systemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                qw.in(FormTemplateHistory::getSystemId, systemIds);
            }
        }
        if (map.get("useId") != null) {
            qw.eq(FormTemplateHistory::getUseId, map.get("useId"));
            qw.orderByDesc(FormTemplateHistory::getVersion);
        } else {
            qw.eq(FormTemplateHistory::getUseId, 0); // 查询正在使用的版本
        }
        qw.orderByDesc(FormTemplateHistory::getId);
        IPage<FormTemplateHistory> iPage = getBaseMapper().selectPage(page, qw);
        List<FormTemplateHistory> templates = iPage.getRecords();
        final ResponseResult<List<SystemData>> responseResult = systemClient.all();
        Map<Long, String> systemMap = null;
        if (responseResult != null && !CollectionUtils.isEmpty(responseResult.getData())) {
            systemMap = responseResult.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
        }
        for (FormTemplateHistory template : templates) {
            if (!CollectionUtils.isEmpty(systemMap))
                template.setSystemName(systemMap.get(template.getSystemId()));
        }
        return iPage;
    }

    public ResponseResult<FormTemplateHistory> getByItemCode(String itemCode) {
        final ResponseResult<ItemData> result = itemClient.getByCode(itemCode);
        ItemData item = null;
        if (result != null)
            item = result.getData();
        FormTemplateHistory formTemplate = null;
        if (item != null) {
            formTemplate = getBaseMapper().selectById(item.getTemplateId());
        }
        return ResponseResult.success(formTemplate);
    }

    public int getMaxVersion(Long id) {
        return getBaseMapper().getMaxVersion(id);
    }

    public Boolean changeVersion(Long oldId, Long newId) {
        FormTemplateHistory oldTemplate = getBaseMapper().selectById(oldId);
        FormTemplateHistory newTemplate = getBaseMapper().selectById(newId);
        if (oldTemplate == null || newTemplate == null) {
            return false;
        }
        newTemplate.setUseId(Long.valueOf(0));
        getBaseMapper().updateById(newTemplate);
        getBaseMapper().updateUseId(oldId, newId);
        return true;
    }
}
